<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop" ref="buttondiv">
          <table style="min-width: 1112px;">
              <tr>
                  <td align="right">检验仪器</td>
                  <td>
                      <rm-ddl-instrument @change="labinstrumentchange" width="200px" v-model="instrid" defaultflag="1"
                          prgno="LIS519" :clearable="false"></rm-ddl-instrument>
                  </td>
                  <td align="left">
                      <el-radio-group v-model="infotype" @change="infotype_changeEvent">
                          <el-radio :label="0">失控原因</el-radio>
                          <el-radio :label="1">失控处理方式</el-radio>
                          <el-radio :label="2">失控处理结果</el-radio>
                          <el-radio :label="7">失控处理备注</el-radio>
                          <el-radio :label="3">临床影响</el-radio>
                          <el-radio :label="4">预防措施</el-radio>
                          <el-radio :label="5">质控评价</el-radio>
                          <el-radio :label="6">审核意见</el-radio>
                      </el-radio-group>
                  </td>
                  <td align="right">
                      <el-button icon="el-icon-search" @click="initialList" v-has="'PINQUERY'">查询(F8)</el-button>
                      <el-button icon="el-icon-edit-outline" @click="BtnAdd(1)" v-has="'PADD'">新增(F2)</el-button>
                      <el-button icon="el-icon-delete-solid" @click="BtnDel(3)" v-has="'PDELETE'">删除(F3)</el-button>
                      <el-button type="primary" icon="el-icon-success" @click="BtnSave()" v-has="'PMODIFY'">保存(F6)
                      </el-button>
                      <el-button icon="el-icon-document-copy" @click="copyData">复制(F9)</el-button>
                      <el-button icon="el-icon-close" @click="BtnExc">退出(X)</el-button>
                  </td>
              </tr>
          </table>
      </div>
      <div class="pagecenter">
          <div ref="xTableDiv" style="height:100%;width:100%">
              <vxe-table show-overflow ref="xTable1" height="auto" width="100%" :loading="loading"
                  :select-config="{ reserve: true }" :data.sync="tableData1" border size="mini"
                  :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow
                  highlight-current-row highlight-hover-row resizable stripe
                  :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" >
                  <vxe-table-column field="instrtxtinfoid" title="ID" width="40px" align="center"
                      header-align="center"></vxe-table-column>
                  <vxe-table-column field="txtinfo" title="文字描述" width="400px" header-align="center"
                    ><template v-slot="{ row, rowIndex }">
                          <el-input style="print" v-model="row.txtinfo" type="textarea" autosize
                              @focus="Focus($event)" @change="TextChange(row)"></el-input>
                      </template></vxe-table-column>
                  <vxe-table-column  field="txtinfokind" title="描述归类" width="150" align="center">
                      <template v-slot="{ row }">
                          <el-autocomplete class="inline-input" v-model="row.txtinfokind"
                              :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect">
                          </el-autocomplete>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="seq" title="序号" :edit-render="{ name: 'input' }" width="60" align="center">
                  </vxe-table-column>
                  <vxe-table-column field="inputcode" title="拼音码"    :edit-render="{ name: 'input', autoselect: true }" width="180"
                      align="center"></vxe-table-column>
                  <vxe-table-column field="defaulttxt" title="默认" width="60" align="center" v-if="infotype == 5">
                      <!-- TODO ||infotype == 6" 目前质控评价也没效果 有需求再加吧 -->
                      <template v-slot="{ row }">
                          <el-checkbox name="defaulttxtId" true-label='1' false-label="0"
                              @change="defaulttxtChangeEvent(row)" v-model="row.defaulttxt"></el-checkbox>
                      </template>
                  </vxe-table-column>
              </vxe-table>
          </div>
      </div>

      <el-dialog width="550px" top="2px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false"
          title="复制文字描述" :visible.sync="popCopyVisible">
          <div style="width: 100%; position: relative">
              <table style="font-size: 12px; white-space: nowrap; width: 100%">
                  <tr>
                      <td style="color: red;">选择复制类型</td>
                      <td>
                          <el-select v-model="copyType" style="width: 400px">
                              <el-option key="current" :label=copyOptopnName value="current">
                              </el-option>
                              <el-option key="all" label="复制所有类型的描述" value="all">
                              </el-option>
                          </el-select>
                      </td>
                  </tr>
                  <tr>
                      <td style="color: red;">复制到其他检验仪器</td>
                      <td>
                          <el-input width="400px" v-model="this.copy_instrids.defaultvaluename" ref="muilt_instrids"
                              key="instrids" placeholder="多选双击开窗" readonly
                              @dblclick.native="DialogSql(copy_instrids)">
                              <el-button slot="append" @click.native="DialogSql(copy_instrids)">选择</el-button>
                          </el-input>
                      </td>
                  </tr>
                  <tr>
                      <td>
                          &nbsp;
                      </td>
                      <td>
                          &nbsp;
                      </td>
                  </tr>
                  <tr>
                      <td>
                      </td>
                      <td style="width: 300px; text-align: right">
                          <el-button @click="btnok()" icon="el-icon-check">确认</el-button>
                          <el-button @click="cancelCopy()" icon="el-icon-close">取消</el-button>
                      </td>
                  </tr>
              </table>
          </div>
      </el-dialog>

      <!--多选弹窗--->
      <el-dialog width="900px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false"
          :title="multichktitle" :visible.sync="dialogMultipleVisible" :destroy-on-close="true"
          v-if="dialogMultipleVisible">
          <rm-SqlMultiple :leftOption="LeftListOptions" :rightOption="RightListOptions" :name="fieldname"
              @change="closedialog"></rm-SqlMultiple>
      </el-dialog>

  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils"; //引入工具类
export default {
  name: "LIS519",
  data() {
      return {
          loading: false,
          instrid: 0,
          infotype: 1,
          tableData1: [],
          txtinfokindList: [],
          keyConfig: {
              isArrow: true,
              isDel: true,
              isTab: true,
              isEdit: true,
              editMethod: ({ seq, row, rowIndex, column, columnIndex, cell }) => { }
          },
          utype: 0,
          seqNum: 0,
          selectRow: null,
          popCopyVisible: false,
          copyOptopnName: "仅复制失控处理方式",
          copyType: "current",
          copy_instrids: {},
          insOption: [],
          dialogMultipleVisible: false,
      };
  },

  //html加载完成之前，执行。执行顺序：父组件-子组件
  created() {
  },
  //.html加载完成后执行。执行顺序：子组件-父组件
  mounted() { },
  watch: {
      instrId(val) {
          this.initialList();
      },
  },
  methods: {
      //初始化数据
      resetData() {
          this.tableData1 = [];
      },
      initialList() {
          //主表查询
          var that = this
          that.loading = true;
          that.resetData();
          that.$tool
              .request({
                  url: "LIS/LIS5/LIS519",
                  method: "post",
                  data: {
                      action: "query",
                      instrid: that.instrid,
                      infotype: that.infotype,
                      prgno: "LIS519",
                  }
              })
              .then(response => {
                  this.insOption = response.insOption;
                  that.tableData1 = response.Data;
                  // 处理描述归类
                  var length = response.Data.length;
                  if (length > 0) {
                      that.txtinfokindList = [];
                      response.Data.forEach(element => {
                          if (element.txtinfokind != null) {
                              that.txtinfokindList.push({ 'value': element.txtinfokind })
                          }
                      })
                      that.seqNum = response.Data[length - 1].seq;
                  }
                  that.loading = false;
              })
              .catch(e => {
                  that.loading = false;
              });
      },
      copyData() {
          this.popCopyVisible = true;
      },
      btnok() {
          if (!this.copyType) {
              this.$message.error("错误：复制类型必填");
              return false;
          }
          if (!this.copy_instrids.defaultvalue) {
              this.$message.error("错误：复制到检验仪器必填");
              return false;
          }
          this.popCopyVisible = false;

          this.$tool
              .request({
                  url: "LIS/LIS5/LIS519",
                  method: "post",
                  data: {
                      action: "saveCopy",
                      instrid: this.instrid,
                      copyType: this.copyType,
                      infotype: this.infotype,
                      copy_instrids: this.copy_instrids.defaultvalue,
                  }
              })
              .then(res => {
                  if (res.errcode == 1) {
                      this.$message.success("复制成功！");
                  } else {
                      this.$message.error("错误：" + res.errmsg);
                  }
              })
      },
      cancelCopy() {
          this.popCopyVisible = false;
      },
      //多选弹窗关闭
      closedialog(value, code, valuename) {
          if (value != "close") {
              this.copy_instrids.defaultvalue = value;
              this.copy_instrids.defaultvaluename = valuename;
          }
          this.dialogMultipleVisible = false;
      },
      //sql多选弹窗
      DialogSql(item) {
          this.fieldname = "检验仪器";
          this.multichktitle = "检验仪器";

          var rowlist = [];
          if (item.defaultvalue) rowlist = item.defaultvalue.split(",");
          this.LeftListOptions = this.insOption.filter(item => rowlist.indexOf(item.data + "") == -1);
          this.RightListOptions = this.insOption.filter(item => rowlist.indexOf(item.data + "") > -1);

          this.dialogMultipleVisible = true;
      },
      //切换仪器时刷新界面
      labinstrumentchange(id, name) {
          this.copy_instrids = {};
          this.instrid = id;
          this.seqNum = 0;
          this.$nextTick(() => {
              this.initialList();
          });
      },

      infotype_changeEvent(label) {
          this.infotype = label;
          switch (label) {
              case 0:
                  this.copyOptopnName = "仅复制失控原因";
                  break;
              case 1:
                  this.copyOptopnName = "仅复制失控处理方式";
                  break;
              case 2:
                  this.copyOptopnName = "仅复制失控处理结果";
                  break;
              case 3:
                  this.copyOptopnName = "仅复制临床影响";
                  break;
              case 4:
                  this.copyOptopnName = "仅复制预防措施";
                  break;
              case 5:
                  this.copyOptopnName = "仅复制质控评价";
                  break;
              case 6:
                  this.copyOptopnName = "仅复制审核意见";
              case 7:
                  this.copyOptopnName = "仅复制失控处理备注";
                  break;
          }
          this.seqNum = 0;
          // this.$nextTick(() => {
          this.initialList();
          // });
      },
      BtnAdd(utype) {
          this.utype = utype;
          var row = {};
          if (this.instrid) {
              this.insertRowAtLast(this.$refs.xTable1, row);
          } else {
              this.$message("请选择仪器");
          }
      },
      BtnSave() {
          var that = this
          if (that.instrid == 0) {
              that.$message("请选择仪器");
              return false;
          }
          //校验 数据
          var record = that.$refs.xTable1.tableData;
          for (let i = 0; i < record.length; i++) {
              let msg = "";
              // msg = that.valid(record[i].seq, "第" + (i + 1) + "行 序号 必须填写！");
              // if (msg) return msg;
              if (!record[i].txtinfo) {
                  msg = "第" + (i + 1) + "行 文字描述 必须填写！"
                  that.$message({
                      message: msg,
                      type: "warning"
                  });
              }
              // msg = that.valid(record[i].txtinfo, "第" + (i + 1) + "行 文字描述 必须填写！");
              if (msg) return msg;
          }
          let allTable1data = that.$refs.xTable1.getTableData().fullData;
          allTable1data.sort((a, b) => {
              return a.seq - b.seq;
          });
          allTable1data.forEach((element, index) => {
              element.seq = (index + 1) * 10;
          });
          let xTable1data = that.$refs.xTable1.getRecordset();
          var params = {
              instrid: that.instrid,
              infotype: that.infotype,
              urec: xTable1data,
              utype: that.utype
          }
          that.$tool
              .request({
                  url: "LIS/LIS5/LIS519",
                  method: "post",
                  data: {
                      action: "save",
                      ...params
                  }
              })
              .then(response => {
                  if (response.errcode == 1) {
                      that.$message.success(response.errmsg);
                      that.initialList();
                  } else {
                      that.$message.error("错误：" + response.errmsg);
                  }
                  that.loading = false;
              })
              .catch(e => {
                  that.loading = false;
              });
      },

      BtnDel(utype) {
          this.utype = utype;
          this.deleteRow(this.$refs.xTable1);
      },

      ///////////////////////////////////工具函数 /////////////////////////////////////////
      insertRowAtLast(xtable, row) {
          this.seqNum += 10;
          row.seq = this.seqNum;
          console.log(row)
          xtable.insertAt(row, -1); //在最后添加一行
          var curow = xtable.getTableData().fullData[xtable.getTableData().fullData.length - 1]; //获取 新加的行对象 row 数据集合
          xtable.setCurrentRow(curow); //高亮显示行
          this.$nextTick(() => {
              xtable.scrollToRow(curow); //待数据加载完成后，延迟 滚动 到行
          });
      },

      //自动加载表格的第一行，并执行回调函数
      loadFirstRow(xTable, func) {
          this.$nextTick(() => {
              // 加载第一行
              var selectrow = xTable.getData(0);
              if (selectrow) {
                  xTable.setCurrentRow(selectrow); //高亮行
                  xTable.scrollToRow(selectrow); //滚动到行
                  if (typeof func == "function") func(selectrow);
              } else {
                  xTable.setCurrentRow(null); //这个不会自动清空
              }
          });
      },

      //删除表格行工具 // 连续 点删除按钮会有失去焦点的问题已解决
      deleteRow(xTable) {
          console.log(xTable.getRemoveRecords())
          var delrow = xTable.getCurrentRow();
          console.log("delrow:" + delrow)
          console.log(" xTable.getRowIndex(delrow):" + xTable.getRowIndex(delrow))
          this.DelIndex = xTable.getRowIndex(delrow);
          xTable.remove(delrow);
          if (this.DelIndex > -1 && xTable.tableData.length > 0) {
              if (xTable.getTableData().fullData.length > this.DelIndex) this.DelIndex = this.DelIndex;
              else this.DelIndex = this.DelIndex - 1;
              var selectrow = xTable.getTableData().fullData[this.DelIndex];
              this.$nextTick(() => {
                  xTable.setCurrentRow(selectrow);
              });
          } else {
              var nowdata = xTable.getTableData().fullData.filter(item => {
                  return item._XID < delrow._XID;
              });
              if (nowdata.length > 0) {
                  var selectrow = nowdata[nowdata.length - 1];
                  this.$nextTick(() => {
                      xTable.setCurrentRow(selectrow);
                  });
              }
          }
      },

      // 描述归类模糊查询
      querySearch(queryString, cb) {
          var txtinfokinds = this.txtinfokindList;
          if (txtinfokinds.length > 0) {
              var results = queryString ? txtinfokinds.filter(this.createFilter(queryString)) : txtinfokinds;
              // console.log(results)
              // 调用 callback 返回建议列表的数据
              cb(results);
          }
      },
      createFilter(queryString) {
          return (txtinfokinds) => {
              return (txtinfokinds.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
      },
      handleSelect(item) {
          console.log(item);
      },
      //获取拼音码
      // getInputCode({ row }) {
      //     // row.inputcode = this.$pub.CreateInputcode(row.txtinfo, this).substring(0, 20);
      //     row.inputcode = this.$pub.CreateInputcode(row.txtinfo, this);
      // },
         Getinputcode(row) {
          row.inputcode = this.$pub.CreateInputcode(row.txtinfo, this, 16);
      },
       Focus(event) {
          event.currentTarget.select();
      },
      TextChange(row) {
          this.Rep(row);
          this.Getinputcode(row);
      },
      Rep(row) {
          var reg = /\n(\n)*( )*(\n)*\n/g;
          row.txtinfo = row.txtinfo.replace(reg, "\n");
      },
      defaulttxtChangeEvent(row) {
          var that = this
          console.log(row)
          that.$refs.xTable1.getTableData().fullData.forEach(element => {
              if (row.instrtxtinfoid != element.instrtxtinfoid) {
                  element.defaulttxt = '0';
              }
          });
          console.log(that.$refs.xTable1.getTableData())
      },
      //关闭按钮
      BtnExc() {
          let index = this.$parent.$refs.itemtags.tagsList.findIndex((m) => m.name == "LIS519");
          this.$parent.$refs.itemtags.tagsList.splice(index, 1);
          this.$router.go(-1);
      },
  },
  beforeRouteEnter(to, from, next) {
      next((vm) => {
          let that = vm;
          let altArr = [];
          document.onkeydown = function (e) {
              let key = window.event.keyCode;
              console.log("key=", key);
              //*组合按键
              if (altArr.length > 0) {
                  //65到90 a到z（A到Z）
                  // //*Alt + C 清除
                  // if (key == 67) {
                  //     this.BtnExc();
                  // }
                  //*Alt + E 退出
                  if (key == 69) {
                      that.BtnExc();
                  }
              } else {
                  if (key == 119) {
                      //F8
                      that.initialList();
                  } else if (key == 113) {
                      //F2
                      that.BtnAdd(1);
                  } else if (key == 114) {
                      //F3
                      that.BtnDel(3);
                  } else if (key == 117) {
                      //F6
                      that.BtnSave();
                  } else if (key == 18) {
                      console.log("按下'ALT'");
                      //按下了alt
                      altArr.push(key);
                  }
                  else if (key == 120) {
                      //F9
                      that.copyData();
                  }
              }
          };
          document.onkeyup = function (e) {
              let key = window.event.keyCode;
              if (key == 18) {
                  altArr = [];
              }
          };
      });
  },
};
</script>

<style scoped>
.pagetop {
  /* left: 0;
  right: 0;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center; */
  border: solid 1px #ccc;
  /* position: absolute;
  z-index: 99; */
  /* text-align: left; */
  /* width: 1132px; */
  height: 36px;
  overflow-x: auto;
  overflow-x: overlay;
}

::-webkit-scrollbar {
  width: 0px;
  height: 5px;
  border: 4px solid white;
}

::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
}

::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.pagetop table {
  border-spacing: 5px;
}

.pagetop .el-radio {
  margin-right: 10px;
}

.pagebottom {
  width: 100%;
  height: 41px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: left;
  position: absolute;
  bottom: 0px;
  font-size: 12px;
  border: solid 1px #ccc;
}

.pagecenter {
  position: absolute;
  top: 40px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  right: 485px;
  left: 0;
}

.middle-right {
  position: absolute;
  top: 0;
  bottom: 2px;
  overflow: visible;
  width: 480px;
  right: 0px;
}

table tr td:nth-child(1) {
  width: 60px;
}

table {
  font-size: 12px;
}

/deep/ .el-input--small .el-input__inner {
  height: 24px !important;
  line-height: 24px !important;
}
</style>
// table tr td:nth-child(odd) {
//     text-align: right;
//     white-space: nowrap;
// }
// table tr td:nth-child(even) {
//     text-align: left;
// }